<template>
	<view>
		<cu-custom bgColor="bg-gradual-blue" :isBack="false">
			<template v-slot:content>卡券</template>
		</cu-custom>

		<view class="cu-bar bg-white search">
			<view class="search-form round">
				<text class="cuIcon-search"></text>
				<input type="text" placeholder="搜索卡券" confirm-type="search" v-model="searchKeyword" @confirm="performSearch" />
			</view>
			<view class="action">
				<button class="cu-btn bg-gradual-blue shadow-blur round" @click="performSearch">搜索</button>
			</view>
		</view>

		<!-- 选项卡 -->
		<scroll-view scroll-x class="bg-white nav">
			<view class="flex text-center">
				<view class="cu-item flex-sub" :class="activeTab === 'platform' ? 'text-orange cur' : ''" @tap="activeTab = 'platform'">
					平台卡券
				</view>
				<view class="cu-item flex-sub" :class="activeTab === 'merchant' ? 'text-orange cur' : ''" @tap="activeTab = 'merchant'">
					商家卡券
				</view>
			</view>
		</scroll-view>

		<!-- 卡券列表 -->
		<view class="padding-lr-sm padding-tb-xs">
			<view v-if="filteredCards.length === 0" class="text-center padding-xl text-gray">
				暂无此类卡券
			</view>
			
			<view class="cu-card coupon" v-for="card in filteredCards" :key="card.card_id" :class="card.is_expired ? 'expired' : ''">
				<view class="cu-item shadow-lg">
					<view class="flex">
						<view class="left">
							<image v-if="card.icon" :src="card.icon" class="avatar"></image>
							<view v-else class="cu-avatar round lg bg-red">
								<text class="cuIcon-ticket"></text>
							</view>
							<view class="text-bold text-sm margin-top-xs name">{{ card.merchant_name }}</view>
						</view>
						<view class="right">
							<view class="flex justify-between align-start">
								<view>
									<view class="text-bold">{{ card.card_name }}</view>
									<view class="text-xs text-gray margin-top-xs">满{{ card.card_threshold }}元可用, 抵扣{{ card.card_price }}元</view>
									<view class="text-xs text-gray margin-top-xs">有效期至: {{ card.valid_date }}</view>
								</view>
								<button class="claim-btn" 
        :class="(card.is_expired || card.claimed) ? 'bg-grey' : 'bg-red'"
        :disabled="card.is_expired || card.claimed"
        @click="claimCard(card)">
    {{ card.claimed ? '已领取' : (card.is_expired ? '已过期' : '去领取') }}
</button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { get, post } from '@/utils/request.js';

const cards = ref([]);
const activeTab = ref('platform'); // 默认显示平台卡券
const searchKeyword = ref('');

const performSearch = () => {
	if (!searchKeyword.value.trim()) {
		uni.showToast({
			title: '请输入搜索内容',
			icon: 'none'
		});
		return;
	}
	uni.navigateTo({
		url: `/pages/search/cardSearch?keyword=${encodeURIComponent(searchKeyword.value)}`
	});
};

// 筛选后的卡券
const filteredCards = computed(() => {
	if (activeTab.value === 'platform') {
		// 平台卡券的 merId 为 0
		return cards.value.filter(card => card.merId === 0);
	}
	// 商家卡券的 merId 不为 0
	return cards.value.filter(card => card.merId !== 0);
});

const claimCard = async (card) => {
	const token = uni.getStorageSync('token');
	if (!token) {
		uni.showToast({
			title: '请先登录',
			icon: 'none',
		});
		setTimeout(() => uni.navigateTo({ url: '/pages/login/login' }), 1500);
		return;
	}

	if (card.claimed) {
		uni.showToast({ title: '您已领取该卡券', icon: 'none' });
		return;
	}

	uni.showLoading({ title: '正在领取...' });

	try {
		const storedUser = uni.getStorageSync('user');
		if (!storedUser) {
			uni.showToast({ title: '无法获取用户信息', icon: 'none' });
			uni.hideLoading();
			return;
		}
		const userData = JSON.parse(storedUser);
		const userId = userData.userId;

		if (!userId) {
			uni.showToast({ title: '无法获取用户ID', icon: 'none' });
			uni.hideLoading();
			return;
		}

		// 只传递必要的信息，后端应负责处理时间戳和校验逻辑
		const payload = {
			userId: userId,
			cardId: card.card_id,
			expireTime: card.expireTime
		};

		const res = await post('/card/addCard', payload);

		uni.hideLoading();

		if (res.data && res.data.code === 200) {
			uni.showToast({ title: '领取成功！', icon: 'success' });
			card.claimed = true; // 更新UI状态
		} else {
			uni.showToast({ title: res.data.msg || '领取失败，请稍后再试', icon: 'none' });
		}
	} catch (error) {
		uni.hideLoading();
		console.error('领取卡券失败:', error);
		uni.showToast({ title: '网络错误，请稍后重试', icon: 'none' });
	}
};

const fetchCards = async () => {
	// 1. 尝试获取用户ID
	let userId = null;
	const storedUser = uni.getStorageSync('user');
	if (storedUser) {
		try {
			const userData = JSON.parse(storedUser);
			userId = userData.userId;
		} catch (e) {
			console.error("解析用户信息失败", e);
		}
	}

	// 2. 构建请求URL
	// 如果用户已登录，则在请求中附带userId，后端会处理领取状态
	// const url = userId ? `/card/getCard?userId=${userId}` : '/card/getCard';
	const url = '/card/allCard'

	try {
		const res = await get(url); // 3. 发起一次请求
		if (res.data && res.data.code === 200 && res.data.msg) {
			cards.value = res.data.msg.map(card => {
				console.log('卡券信息',res)
				const isExpired = new Date(card.endTime) < new Date();
				return {
					...card,
					card_id: card.cardId,
					card_name: card.cardName,
					card_price: card.cardPrice,
					card_threshold: card.condition,
					merchant_name: card.merId === 0 ? '平台通用' : card.merName,
					valid_date: card.endTime.split('T')[0],
					is_expired: isExpired,
					// 4. 直接使用后端返回的字段
					claimed: card.claimedByUser || false
				};
			});
		} else {
			uni.showToast({ title: '加载卡券失败', icon: 'none' });
		}
	} catch (error) {
		console.error('获取卡券列表失败:', error);
		uni.showToast({ title: '网络错误', icon: 'none' });
	}
};

onMounted(() => {
	fetchCards();
});
</script>

<style scoped>

.coupon {
	margin-top: 20rpx;
}
.coupon .cu-item {
	border-radius: 16rpx;
	overflow: hidden;
}
.coupon .left {
	width: 200rpx;
	background-color: #fff8f8;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 20rpx;
	border-right: 2rpx dashed #eee;
}
.coupon .left .avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
}
.coupon .left .name {
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	width: 100%;
	text-align: center;
}
.coupon .right {
	flex: 1;
	padding: 20rpx;
	background-color: #ffffff;
}
.expired {
	filter: grayscale(100%);
	opacity: 0.7;
}
.claim-btn {
    min-width: 160rpx; /* 加长宽度 */
    height: 60rpx; /* 保持原有高度 */
    border-radius: 30rpx; /* 圆形按钮 */
    text-align: center;
    font-size: 28rpx;
    padding: 0 20rpx;
    line-height: 60rpx;
    white-space: nowrap;
    box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
    transition: all 0.2s ease;
}
/* 按钮激活状态 */
.claim-btn:active:not([disabled]) {
    transform: scale(0.95);
}

/* 按钮禁用状态 */
.claim-btn[disabled] {
    opacity: 0.6;
}
</style>